const axios = require('axios');

// 测试API基础URL
const API_BASE_URL = 'http://localhost:3000/api';

// 测试用户登录并访问受保护的用户接口
async function testAuthFlow() {
  try {
    console.log('Testing authentication flow...');
    
    // 1. 登录获取token
    console.log('\n1. Logging in...');
    const loginResponse = await axios.post(`${API_BASE_URL}/users/login`, {
      username: 'testuser',
      password: 'testpassword'
    });
    
    console.log('Login successful!');
    console.log('Token:', loginResponse.data.token);
    
    const token = loginResponse.data.token;
    
    // 2. 使用token访问受保护的用户接口
    console.log('\n2. Accessing protected user list with token...');
    const usersResponse = await axios.get(`${API_BASE_URL}/users`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });
    
    console.log('User list retrieved successfully!');
    console.log('Users count:', usersResponse.data.length);
    
    // 3. 尝试不带token访问受保护的接口（应该失败）
    console.log('\n3. Trying to access protected endpoint without token...');
    try {
      await axios.get(`${API_BASE_URL}/users`);
      console.log('ERROR: Should have failed!');
    } catch (error) {
      if (error.response && error.response.status === 401) {
        console.log('SUCCESS: Access correctly denied without token');
      } else {
        console.log('ERROR: Unexpected response:', error.message);
      }
    }
    
    console.log('\nAuthentication flow test completed!');
  } catch (error) {
    console.error('Test failed:', error.message);
    if (error.response) {
      console.error('Response data:', error.response.data);
      console.error('Status code:', error.response.status);
    }
  }
}

testAuthFlow();
